<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Db;
class Index extends Frontend
{

    // protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    public function index()
    {
        //查询日期
        // $datelist=db('codes')->group('add_day')->order('add_day desc')->select();
        // foreach ($datelist as $key => &$value) {
        //     # code...
        //     $codelist=db('codes')->where('add_day', $value['add_day'])->order('id asc')->select(); 
        //     // var_dump($codelist);
        //     $value['codelist']=$codelist; 
        // }
        $datelist=db('ka')->where('isdel',0)->order('id desc')->select();
        foreach ($datelist as $key => &$value) {
            # code...
            $codelist=db('codes')->where('ka_id', $value['id'])->order('id asc')->select(); 
            // var_dump($codelist);
            $value['codelist']=$codelist; 
        }
        $this->assign('datelist',$datelist);
        return $this->view->fetch();
    }
    function addcode()
    {
        
        //查询日期
        $datelist=db('codes')->group('add_day')->order('add_day desc')->select();
        foreach ($datelist as $key => &$value) {
            # code...
            $codelist=db('codes')->where('add_day', $value['add_day'])->order('id asc')->select(); 
            // var_dump($codelist);
            $value['codelist']=$codelist; 
        }
        $this->assign('datelist',$datelist);
        return $this->view->fetch();
    }
    
    //生成
    function shengcheng()
    {
        $count=(int)$this->request->param("count");
        $title=$this->request->param("title");
        if(!trim($title))
        {
            $this->error('请输入备注');
        }
        if(!$count)
        {
            $this->error('请输入生成数量');
        }
        
        // 如果需要生成多个码，可以这样做：  
        Db::startTrans();
        $codes = []; 
        $data_ka['title']=$title;
        $data_ka['addtime']=time();
        $ka_id=db('ka')->insertGetId($data_ka); 
        for ($i = 0; $i < $count; $i++) { // 假设我们要生成10个码  
            $newCode = $this->generateRandomCode(); 
            // 检查数据库中是否已经存在这个码  
            $exists = db('codes')->where('codes', $newCode)->find();  
            if (!$exists) { // 如果不存在，则添加到数组中  
                $codes[] = [  
                    'ka_id' =>$ka_id,
                    'codes' => $newCode,  
                    'add_time' => time(),  
                    'add_day' => date('Y-m-d')  
                ];  
            } else {  
                // 如果存在，可以选择重新生成或者做一些其他处理  
                // 这里我们选择重新生成直到得到一个不重复的码  
                $i--; // 减一以确保循环继续尝试生成新的码  
            } 
        } 
        if($codes)
        {
            $res=db('codes')->insertAll($codes);
            if($res)
            {
                Db::commit();
                $this->success('成功');
            }
            else
            {
                Db::rollback();
                $this->error('生成失败');
            }
        }
        else
        {
            //没有生成码
            Db::rollback();
            $this->error('未生成');
        }
        


    }
    //获取列表
    function getcodelist()
    {
        $day=$this->request->param("day");
        $codelist=db('codes')->where('add_day', $day)->order('id asc')->select();  
        // $this->success('成功',$codelist);
        return json_encode(['code'=>1,'data'=>$codelist]);
    }
    function generateRandomCode() {  
        // 字符集：数字+小写字母+大写字母  
        $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';  
        $length = strlen($chars);  
      
        // 确保至少有一个数字和一个字母  
        $randomDigit = $chars[random_int(0, 9)]; // 强制选择一个数字  
        $randomLetter = $chars[random_int(10, 35)] . $chars[random_int(36, 61)]; // 强制选择一个字母（小写或大写）  
      
        // 剩余的10个字符可以是任何字符  
        $remainingChars = '';  
        for ($i = 0; $i < 10; $i++) {  
            $remainingChars .= $chars[random_int(0, $length - 1)];  
        }  
      
        // 打乱剩余的10个字符，以确保它们不是顺序的  
        $remainingChars = str_shuffle($remainingChars);  
      
        // 组合成最终的12位码  
        $code = $randomDigit . $randomLetter . $remainingChars;  
      
        // 如果需要，可以进一步打乱整个码  
        $code = str_shuffle($code);  
      
        // 截取前12个字符（理论上这一步是多余的，因为我们已经确保了长度为12）  
        $code = substr($code, 0, 12);  
        //判断是否存在
        
      
        return $code;  
    }  
    //导出
    function export()
    {
        $day=$this->request->param("day");
        vendor('PHPExcel.PHPExcel');
            //添加标题到数组头部
            // $file_name = '礼品卡' . date('Y-m-d_His') . '.xls';
            $file_name = '礼品卡' . date('Y-m-d_His') . '.xls';
            $PHPExcel = new \PHPExcel();
            // print_r($PHPExcel);die;
            
            $PHPSheet = $PHPExcel->getActiveSheet();
            // 设置A列的宽度为20
               $PHPSheet->getColumnDimension('A')->setWidth(50);
         
            $PHPSheet->setTitle("表格一");
            
           
  
            
            $PHPSheet->setCellValue("A1", "线下礼品卡激活码导入模板");
            $PHPSheet->setCellValue("A2", "线下礼品卡激活码(注意！不要写入纯数字的激活码和重复的激活码，单个卡号码长度不超过30，从此行往下增加激活码)");
            $i = 3;
           
            if($day)
            {
                $list=db('codes')->where(['ka_id'=>$day])->order('id asc')->select();
                // var_dump($list);die;
            }
            else
            {
                $list=db('codes')->order('id asc')->select();
            }
            
            foreach ($list as $keys => $value) {    
                
                $PHPSheet->setCellValue('A' . $i, '' . $value['codes']);
                
            
                $i++;
            }
            
           
            $PHPWriter = \PHPExcel_IOFactory::createWriter($PHPExcel, "Excel5");
          
            header("Content-Type: application/vnd.ms-excel;charset=utf-8");
            header('Content-Disposition: attachment;filename=' . $file_name);
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            $PHPWriter->save("php://output");
    }
      

      
     
      


}
